/*
 * Copyright 2007 Jeffrey Palm
 */

import java.io.*;
import java.util.*;

/**
 * Creates a PHP world
 */
class PHPSink extends AbstractOOSink {

  PHPSink(File outdir) {super(outdir);}

  // --------------------------------------------------
  // AbstractOOSink
  // --------------------------------------------------

  String typeHeader(World.Type t) {return "<?php\ninclude_once 'support.php';";}

  String typeFooter(World.Type t) {return "?>";}

  boolean wantsPublic() {return false;}

  String getExtends() {return null;}

  String formatMember(World.Decl d) {return "var $" + d.getName();}

  String constructorStart(String name) {return "function " + name;}

  String methodStart(World.Decl d) {return "function";}

  boolean useParamType() {return false;}

  String thiz(String name) {return "$this->" + name;}

  String var(String name) {return "$" + name;}

  String lineComment() {return "#";}

  String comment(String s) {return "/* " + s + " */";}

  String openBrace() {return "{";}
  String closeBrace() {return "}";}

  void createMethodBody(PrintStream out, World.Type t, World.Decl d) {
    Support.Param[] ps = new Support.Param[d.getParams().size()];
    int i = 0;
    for (World.Param p : d.getParams()) {
      String name = p.getName();
      String value;
      if (p.getType() != null) {
        value = p.getName();
      } else {
        value = getInvokeMethod(t,d.getParams(),p);
      }
      ps[i++] = Support.newParam(name,"' . urlencode(" + value + ") . '"); // unquote it
    }
    String url = Support.getURL(t.getName(),d.getName(),ps, new boolean[]{true,false});
    out.print(tab + tab + "return extractResult('" + url + "');");

  }

  // --------------------------------------------------
  // FileSink
  // --------------------------------------------------

  String getFileName(World.Type t) {
    return t.getName() + ".class.php";
  }

  String name() {
    return "php";
  }

  /** Write out include.php */
  void postpareRest() {
    try {
      PrintStream out = new PrintStream(new FileOutputStream(new File(getOutdir(),"include.php")));
      out.println("<?php");
      for (String n : getFileNames()) {
        out.println("include_once '" + n + "';");
      }
      out.println("?>");
      out.close();
    } catch (Exception e) {e.printStackTrace();}
  }

}